from django.db import connection
from django.db.models import Q
from django.http import JsonResponse
from django.views import View
from django.utils import timezone
from django.core.cache import cache
from app.models import *
from app.RoleMethod.PublicMethod import PublicMethod
import time
import uuid
import json
publicMethod = PublicMethod()


class CreateClass(View):
    """
    模块: 获取团队信息,创建团队,删除团队
    接口信息:
        GET:
            token：token认证
        POST:
            token：token认证
            team_name: 队伍名称
            team_introduce: 团队介绍
            team_member: 团队人员列表
            team_teacher: 指导老师
            team_school: 团队所属学校
        DELETE:
            token：token认证
            class_id: 团队ID
    返回信息:
        GET:
            status: 验证状态[True|False](boolean)
            message: team消息
        POST:
            status: 验证状态[True|False](boolean)
            message: 提示信息
        DELETE:
            status: 验证状态[True|False](boolean)
            message: 提示信息
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        page = request.GET.get('page')
        total = request.GET.get('total')
        text = request.GET.get('text')
        course_id = request.GET.get('course_id')
        class_id = request.GET.get('class_id')
        school_id = request.GET.get('school_id')
        college_id = request.GET.get('college_id')
        print(course_id, class_id, school_id, college_id)
        classes = Class.objects.all()
        if text:
            classes = classes.filter(Q(class_name__contains=text))
        if course_id:
            classes = classes.filter(course_id=course_id)
        if class_id:
            classes = classes.filter(class_id=class_id)
        if school_id:
            classes = classes.filter(class_school=school_id.split(',')[-1])
        if college_id:
            classes = classes.filter(class_college=college_id)
        class_num = classes.count()
        if not total:
            total = '0'
        if total != '0':
            classes = classes[(int(page) - 1) * int(total): int(page) * int(total)]
        class_list = []
        member = 0
        for item in classes:
            user_list = []
            # users = ClassUser.objects.filter(class_id=item.class_id)
            # for user in users:
            #     user_nick = User.objects.filter(user_id=user.user_id).first()
            #     if not user_nick:
            #         user_nick = user.user_id
            #     else:
            #         user_nick = user_nick.user_nick
            #     user_list.append({
            #         'user_id': user.user_id,
            #         'user_nick': user_nick,
            #         'user_type': user.user_type,
            #         'add_time': user.add_time,
            #         'user_status': user.user_status,
            #     })
            school = School.objects.filter(school_id=item.class_school).first()
            if not school:
                class_school = {
                    'school_id': item.class_school,
                    'school_name': '',
                }
            else:
                class_school = {
                    'school_id': item.class_school,
                    'school_name': school.school_name,
                }
            college = College.objects.filter(college_id=item.class_college).first()
            if not college:
                class_college = {
                    'college_id': item.class_college,
                    'college_name': '',
                }
            else:
                class_college = {
                    'college_id': item.class_college,
                    'college_name': college.college_name,
                }
            class_list.append({
                'class_id': item.class_id,
                'class_name': item.class_name,
                'class_creator': item.class_creator,
                'create_time': item.create_time,
                'class_introduce': item.class_introduce,
                'class_type': item.class_type,
                'course_id': item.course_id,
                'class_school': class_school,
                'class_college': class_college,
                'class_invitation': item.class_invitation,
                'code_time': item.code_time,
                'user_list': user_list,
            })
            member += 1
        return JsonResponse({'status': True, 'message': class_list, 'total': class_num})

    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        class_name = request.POST.get('class_name')
        class_introduce = request.POST.get('class_introduce')
        class_note = request.POST.get('class_note')
        course_id = request.POST.get('course_id')
        class_school = request.POST.get('class_school')
        class_college = request.POST.get('class_college')
        class_teacher = request.POST.get('class_teacher')
        try:
            class_teacher = class_teacher.split(',')
            class_student = request.POST.get('class_student')
            class_student = class_student.split(',')
        except:
            print("这里出了问题")
        if course_id != '0':
            class_type = 1
        else:
            class_type = 0
        print(class_name, class_introduce, class_note, class_type, course_id, class_school, class_college, class_teacher, class_student)
        the_class = Class.objects.create(
            class_name=class_name,
            class_creator=user_id,
            create_time=timezone.now(),
            class_introduce=class_introduce,
            class_note=class_note,
            class_type=class_type,
            course_id=course_id,
            class_school=class_school,
            class_college=class_college,
            code_time=timezone.now(),
        )
        for user_id in class_teacher:
            ClassUser.objects.create(
                class_id=the_class.class_id,
                user_id=user_id,
                course_id=course_id,
                user_type=1,
                add_time=timezone.now(),
                add_type=2,
            )
        for user_id in class_student:
            ClassUser.objects.create(
                class_id=the_class.class_id,
                user_id=user_id,
                course_id=course_id,
                user_type=0,
                add_time=timezone.now(),
                add_type=2,
            )
        return JsonResponse({'status': True, 'message': '创建成功'})

    def put(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        class_id = request.GET.get('class_id')
        class_name = request.GET.get('class_name')
        class_introduce = request.GET.get('class_introduce')
        class_note = request.GET.get('class_note')
        class_school = request.GET.get('class_school')
        class_college = request.GET.get('class_college')
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'status': False, 'message': '用户未完善信息'})
        the_class = Class.objects.filter(class_id=class_id).first()
        if not the_class:
            return JsonResponse({'status': False, 'message': '这个班级不存在'})
        users = []
        if the_class.course_id:
            users = ClassUser.objects.filter(course_id=the_class.course_id, user_type=1).values_list('user_id')
        if the_class.class_creator != user_id and user.user_power not in [0, 1] and user_id not in users:
            return JsonResponse({'status': False, 'message': '你没有权限'})
        if class_name:
            the_class.class_name = class_name
        if class_introduce:
            the_class.class_introduce = class_introduce
        if class_note:
            the_class.class_note = class_note
        if class_school:
            the_class.class_school = class_school
        if class_college:
            the_class.class_college = class_college
        the_class.save()
        return JsonResponse({'status': True, 'message': '修改成功'})

    def delete(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        class_id = request.GET.get('class_id')
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'status': False, 'message': '用户未完善信息'})
        the_class = Class.objects.filter(class_id=class_id).first()
        if not the_class:
            return JsonResponse({'status': False, 'message': '这个班级不存在'})
        users = []
        if the_class.course_id:
            users = ClassUser.objects.filter(course_id=the_class.course_id, user_type=1).values_list('user_id')
        if the_class.class_creator != user_id and user.user_power not in [0, 1] and user_id not in users:
            return JsonResponse({'status': False, 'message': '你没有权限'})
        the_class.delete()
        return JsonResponse({'status': True, 'message': '删除成功'})


class AddCourseClass(View):
    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_id = request.POST.get("course_id")
        class_id = request.POST.get("class_id")
        print(class_id, course_id)
        is_exist = Class.objects.filter(class_id=class_id).first()
        if not is_exist:
            class_name = request.POST.get("class_name")
            Class.objects.create(
                class_name=class_name,
                class_creator=user_id,
                create_time=timezone.now(),
                class_introduce="这是一个课程班级属于课程"+str(course_id),
                class_type=1,
                course_id=course_id,
            )
            class_id = Class.objects.filter(class_name=class_name).first().class_id
        CourseClass.objects.create(
            course_id=course_id,
            course_class=class_id,
            class_type=0
        )
        class_info = Class.objects.filter(class_id=class_id).first()
        if not class_info:
            return JsonResponse({"status": False, "message": "课程未存在"})
        else:
            class_info.course_id = course_id
            class_info.save()
        return JsonResponse({"status": True, "message": "添加成功"})


class CreateCode(View):
    def get(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        class_id = request.GET.get('class_id')
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        the_class = Class.objects.filter(class_id=class_id).first()
        if not the_class:
            return JsonResponse({'status': False, 'message': '团队不存在'})
        users = []
        if the_class.course_id:
            users = ClassUser.objects.filter(course_id=the_class.course_id, user_type=1).values_list('user_id')
        if the_class.team_creator != user_id and user_id not in users:
            return JsonResponse({'status': False, 'message': '无权限'})
        code = str(uuid.uuid1())
        the_class.invitation_code = code[0:8]
        cache.set(f"team_{class_id}", the_class.invitation_code, 259200)
        end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time() + 259200)))
        the_class.code_time = int(time.time()) + 259200
        the_class.save()
        return JsonResponse({'status': True, 'message': {'code': the_class.invitation_code, 'time': end_time}})


class JoinClass(View):
    def post(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        code = request.POST.get('code')
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        the_class = Class.objects.filter(invitation_code=code, code_time__gte=int(time.time())).first()
        if not the_class:
            return JsonResponse({'status': False, 'message': '邀请码不正确'})
        else:
            class_user = ClassUser.objects.filter(class_id=the_class.team_id, user_id=user_id).first()
            if class_user:
                return JsonResponse({'status': False, 'message': '已加入该团队!'})
            ClassUser.objects.create(
                class_id=the_class.class_id,
                user_id=user_id,
                add_time=timezone.now(),
                add_type=0,
                user_type=0,
                course_id=the_class.course_id
            )
            return JsonResponse({'status': True, 'message': '加入成功'})

    def delete(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        class_id = request.GET.get('class_id')
        delete_user = request.GET.get('user_id')
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'status': False, 'message': '用户未完善信息'})
        if not delete_user:
            delete_user = user_id
        the_class = Class.objects.filter(class_id=class_id).first()
        users = []
        if the_class.course_id:
            users = ClassUser.objects.filter(course_id=the_class.course_id, user_type=1).values_list('user_id')
        if user_id == delete_user or the_class.team_creator == user_id or user_id in users:
            class_user = ClassUser.objects.filter(class_id=class_id, user_id=delete_user).first()
            class_user.delete()
        else:
            return JsonResponse({'status': False, 'message': '无权限'})
        return JsonResponse({'status': True, 'message': '删除完成'})

class AdminCatchStudent(View):
    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户登录错误"})
        class_id = request.POST.get("class_id")
        course_id = request.POST.get("course_id")
        user_list = request.POST.get("user_list")
        print(class_id, course_id, user_list)
        user = User.objects.filter(user_id=user_list).first()
        if not user:
            return JsonResponse({'status': False, 'message': '用户不存在'})
        # user_list = json.loads(request.POST.get("user_list"))
        # users = user_list.split(',')
        # for user in user_list:
        #     ClassUser.objects.create(
        #         class_id=class_id,
        #         user_id=user,
        #         course_id=course_id,
        #         user_type=0,
        #         add_time=timezone.now(),
        #         add_type=2,
        #     )
        class_user = ClassUser.objects.filter(user_id=user_list, course_id=course_id).first()
        if class_user:
            return JsonResponse({'status': False, 'message': '用户已存在'})
        ClassUser.objects.create(
            class_id=class_id,
            user_id=user_list,
            course_id=course_id,
            user_type=0,
            add_time=timezone.now(),
            add_type=2,
        )
        return JsonResponse({'status': True, 'message': '添加成功'})

    def delete(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        class_id = request.GET.get("class_id")
        course_id = request.GET.get("course_id")
        student_id = request.GET.get("user_id")
        print(class_id, course_id, student_id)
        student = ClassUser.objects.filter(class_id=class_id, course_id=course_id, user_id=student_id)
        if not student_id:
            return JsonResponse({"status": False, "message": "没有这个学生"})
        TaskSubmit.objects.filter(task_class=class_id, task_course=course_id, task_user=student_id).delete()
        ChapterUser.objects.filter(user_id=student_id, class_id=class_id).delete()
        student.delete()
        return JsonResponse({"status": True, "message": "删除成功"})


class JoinCourse(View):
    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        course_id = request.POST.get("course_id")
        print(course_id, user_id)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        class_name = Class.objects.filter(course_id=course_id, class_type=2).first()
        is_exist = ClassUser.objects.filter(user_id=user_id, course_id=course_id).first()
        if not class_name:
            return JsonResponse({'status': False, 'message': '班级不存在'})
        if not is_exist:
            ClassUser.objects.create(
                class_id=class_name.class_id,
                user_id=user_id,
                course_id=course_id,
                user_type=0,
                add_time=timezone.now(),
                add_type=1,
            )
        return JsonResponse({"status": True, 'message': '加入成功'})


